package com.hanma.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hanma.bean.Comments;
import com.hanma.bean.Record;
import com.hanma.bean.User;
import com.hanma.service.CommentsService;
import com.hanma.service.RecordService;
import com.hanma.service.UserService;
import com.hanma.service.impl.CommentsServiceImpl;
import com.hanma.service.impl.RecordServiceImpl;
import com.hanma.service.impl.UserServiceImpl;
import com.hanma.util.FileUtil;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet({"/signup.do","/login.do","/signupAction.do","/loginAction.do","/my.do","/myAction.do","/myHeadAction.do"})
//前端用户管理页面
public class UserServlet1 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String path = req.getServletPath();
		HttpSession session = req.getSession();
		req.setCharacterEncoding("utf-8");
		UserService service = new UserServiceImpl();
		CommentsService commentsService = new CommentsServiceImpl();
		RecordService recordService = new RecordServiceImpl();
		//转发到注册页面
		if(path.equals("/signup.do")) {
			req.getRequestDispatcher("/home/signup.jsp").forward(req, resp);
		}
		//提交注册页面
		else if(path.equals("/signupAction.do")) {
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			String con_password = req.getParameter("con_password");
			String head = "/message/home/img/4.jpeg";
			User user = new User(username,password,con_password,head);
			boolean flag = service.findByName(user.getUsername());
			if(flag) {
				String fail="用户名已存在，请重新输入";
				req.setAttribute("fail", fail);
				req.getRequestDispatcher("/home/signup.jsp").forward(req, resp);
				return;
			}else {
				String token=(String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
				//删除 Session中的验证码 以便这个验证码后续还能用
				req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
				// 获取前端输入的验证码
				String captcha=req.getParameter("captcha");
				if(token==null || !token.equals(captcha)){
					//验证码不一样一样
					String promptToken="验证码错误，请重新输入";
					req.setAttribute("promptToken", promptToken);
					req.getRequestDispatcher("/home/signup.jsp").forward(req, resp);
					return;
				}
				boolean result = service.insert(user);
				if(!result) {
					req.getRequestDispatcher("/home/signup.jsp").forward(req, resp);
					return;
				}
				resp.sendRedirect("/message/home/login.jsp");
			}
			
		}
		//转发到登录页面
		else if(path.equals("/login.do")) {
			req.getRequestDispatcher("/home/login.jsp").forward(req, resp);
		}
		//提交登录页面
		else if(path.equals("/loginAction.do")) {
			String name = req.getParameter("name");
			String password = req.getParameter("password");
			User user = service.find(name,password);
			if(user == null) {
				req.getRequestDispatcher("/home/login.jsp").forward(req, resp);
				return;
			}
			req.setAttribute("user", user);
			req.getRequestDispatcher("/signIndex.do").forward(req, resp);
		}
		//接受用户数据并转发到个人中心页面
		else if(path.equals("/my.do")) {
			Integer location = 1;
			Integer id = (Integer)session.getAttribute("uid");
			if(req.getParameter("location") != null){
				location = Integer.parseInt(req.getParameter("location"));
			}
			User user = service.findById(id);
			//获取用户的评论列表
			List<Comments> commentsList = commentsService.findAllUser(id);
			req.setAttribute("commentsNum", commentsList.size());
			if(location == 2) {
				Integer currentPage = 1;
				if(req.getParameter("currentPage") != null) {
					currentPage = Integer.parseInt(req.getParameter("currentPage"));
				}
				Integer size = 4;
				Integer totalPage = commentsList.size() % 4 == 0 ? commentsList.size() / 4 : (commentsList.size() / 4 + 1);
				Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
				Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
				req.setAttribute("totalPage", totalPage);
				req.setAttribute("currentPage", currentPage);
				req.setAttribute("prePage", prePage);
				req.setAttribute("nextPage", nextPage);
				Integer start = (currentPage - 1) * size;
				commentsList = commentsService.findAllUser(id,start, size);
			}
			//获取用户的记录列表
			List<Record> recordList = recordService.findAll(id);
			req.setAttribute("recordNum", recordList.size());
			if(location == 3) {
				Integer currentPage = 1;
				if(req.getParameter("currentPage") != null) {
					currentPage = Integer.parseInt(req.getParameter("currentPage"));
				}
				Integer size = 4;
				Integer totalPage = recordList.size() % 4 == 0 ? recordList.size() / 4 : (recordList.size() / 4 + 1);
				Integer prePage = currentPage - 1 <= 0 ? 1 : currentPage - 1;
				Integer nextPage = currentPage + 1 >= totalPage ? totalPage : currentPage + 1;
				req.setAttribute("totalPage", totalPage);
				req.setAttribute("currentPage", currentPage);
				req.setAttribute("prePage", prePage);
				req.setAttribute("nextPage", nextPage);
				Integer start = (currentPage - 1) * size;
				recordList = recordService.findAll(id,start, size);
			}
			req.setAttribute("recordList",recordList);
			req.setAttribute("location", location);
			req.setAttribute("user", user);
			req.setAttribute("commentsList", commentsList);
			req.getRequestDispatcher("/home/my.jsp").forward(req, resp);
		}
		//个人中心提交修改的个人信息
		else if(path.equals("/myAction.do")) {
			Integer id = (Integer)session.getAttribute("uid");
			String nickname = req.getParameter("nickname");
			String tel = req.getParameter("tel");
			String email = req.getParameter("email");
			String new_password = req.getParameter("new_password");
			String password = req.getParameter("password");
			User oldUser = service.findById(id);
			if(new_password == null || new_password.equals("")) {
				new_password = password;
			}else {
				User user = new User(id,nickname,new_password,tel,email);
				boolean flag = service.update(user, id);
				if(!flag) {
					req.getRequestDispatcher("/home/my.jsp").forward(req, resp);
				}
				if(!nickname.equals(oldUser.getNickname())){
					commentsService.updateNickname(id, nickname);
				}
				req.setAttribute("user", user);
				req.getRequestDispatcher("/login.do").forward(req, resp);
			}
			User user = new User(id,nickname,new_password,tel,email);
			boolean flag = service.update(user, id);
			if(!flag) {
				req.getRequestDispatcher("/home/my.jsp").forward(req, resp);
			}
			if(!nickname.equals(oldUser.getNickname())){
				commentsService.updateNickname(id, nickname);
			}
			req.setAttribute("user", user);
			req.getRequestDispatcher("/signIndex.do").forward(req, resp);
		}
		//修改头像
		else if(path.equals("/myHeadAction.do")) {
			Integer id = (Integer)session.getAttribute("uid");
			String url = this.getServletContext().getRealPath("/upload");
			String uploadPath = FileUtil.upload(req, url);
			String headImg = "/message/upload/"+uploadPath;
			boolean flag = service.updateHead(id, headImg);
			if(!flag) {
				req.getRequestDispatcher("/home/my.jsp").forward(req, resp);
			}
			commentsService.updateHead(id, headImg);
			req.getRequestDispatcher("/my.do").forward(req, resp);
		}
	}
	
}
